//
//  UIImage+BaseFramework.m
//  LotteryClient
//
//  Created by Sunyon 14-4-8.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "UIImage+BaseFramework.h"
#import "BaseDefines.h"
#import <ImageIO/ImageIO.h>

@implementation UIImage (BaseFramework)

- (UIImage *)resizeImageWithCapInsets:(UIEdgeInsets)capInsets
{
    CGFloat systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    UIImage *image = nil;
    if (systemVersion >= 5.0)
	{
        image = [self resizableImageWithCapInsets:capInsets];
        return image;
    }
    image = [self stretchableImageWithLeftCapWidth:capInsets.left topCapHeight:capInsets.top];
    return image;
}


@end

@implementation UIImage (Addition)
+ (id)imageLoad:(NSString *)file
{
    NSString *str = [[NSBundle mainBundle] pathForResource:[file stringByDeletingPathExtension]
													ofType:[file pathExtension]];
    return [UIImage imageWithContentsOfFile:str];
}


#pragma mark -

+ (UIImage *)animatedGIFWithData:(NSData *)data
{
    if (!data) {
        return nil;
    }
	
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
	
    size_t count = CGImageSourceGetCount(source);
    NSMutableArray* images = [NSMutableArray array];
	
    NSTimeInterval duration = 0.0f;
	
    for (size_t i = 0; i < count; i++) {
        CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
		
        NSDictionary* frameProperties = (__bridge NSDictionary*)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
        duration += [[[frameProperties objectForKey:(NSString*)kCGImagePropertyGIFDictionary] objectForKey:(NSString*)kCGImagePropertyGIFDelayTime] doubleValue];
		
        [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
		
        CGImageRelease(image);
    }
	
    CFRelease(source);
	
    if (!duration) {
        duration = (1.0f/10.0f)*count;
    }
	
    return [UIImage animatedImageWithImages:images duration:duration];
}

+(UIImage*)animatedGIFNamed:(NSString *)name {
    CGFloat scale = [UIScreen mainScreen].scale;
	
    if (scale > 1.0f) {
        NSString* retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
		
        NSData* data = [NSData dataWithContentsOfFile:retinaPath];
		
        if (data) {
            return [UIImage animatedGIFWithData:data];
        }
		
        NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
		
        data = [NSData dataWithContentsOfFile:path];
		
        if (data) {
            return [UIImage animatedGIFWithData:data];
        }
		
        return [UIImage imageNamed:name];
    }
    else {
        NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
		
        NSData* data = [NSData dataWithContentsOfFile:path];
		
        if (data) {
            return [UIImage animatedGIFWithData:data];
        }
		
        return [UIImage imageNamed:name];
    }
}

-(UIImage*)animatedImageByScalingAndCroppingToSize:(CGSize)size {
    if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
        return self;
    }
	
    CGSize scaledSize = size;
	CGPoint thumbnailPoint = CGPointZero;
	
    CGFloat widthFactor = size.width / self.size.width;
    CGFloat heightFactor = size.height / self.size.height;
    CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor :heightFactor;
    scaledSize.width = self.size.width * scaleFactor;
    scaledSize.height = self.size.height * scaleFactor;
    if (widthFactor > heightFactor) {
        thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
    } else if (widthFactor < heightFactor) {
        thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
    }
	
    NSMutableArray* scaledImages = [NSMutableArray array];
	
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
	
    for (UIImage* image in self.images) {
        [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
		
        [scaledImages addObject:newImage];
    }
	
    UIGraphicsEndImageContext();
	
	return [UIImage animatedImageWithImages:scaledImages duration:self.duration];
}

@end


@implementation UIImage (Stretch)

- (UIImage *)stretchableImageByCenter
{
	CGFloat leftCapWidth = floorf(self.size.width / 2);
	if (leftCapWidth == self.size.width / 2)
	{
		leftCapWidth--;
	}
	
	CGFloat topCapHeight = floorf(self.size.height / 2);
	if (topCapHeight == self.size.height / 2)
	{
		topCapHeight--;
	}
	
	return [self stretchableImageWithLeftCapWidth:leftCapWidth
									 topCapHeight:topCapHeight];
}

- (UIImage *)stretchableImageByWidthCenter
{
	CGFloat leftCapWidth = floorf(self.size.width / 2);
	if (leftCapWidth == self.size.width / 2)
	{
		leftCapWidth--;
	}
	
	return [self stretchableImageWithLeftCapWidth:leftCapWidth
									 topCapHeight:0];
}

- (NSInteger)rightCapWidth
{
	return (NSInteger)self.size.width - (self.leftCapWidth + 1);
}


- (NSInteger)bottomCapHeight
{
	return (NSInteger)self.size.height - (self.topCapHeight + 1);
}

@end


@implementation UIImage (Color)

+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)whiteGradiantImageWithSize:(CGSize)size
{
	//    CGFloat colors[] =
	//    {
	//        1, 1, 1, 0.6,
	//        1, 1, 1, 0.0,
	//    };
    
    CGFloat colors[] =
    {
        0, 0, 0, 0.4,
        0, 0, 0, 0.0,
    };
    
    CGFloat locations[2] = { 0.0, 1.0 };
    size_t num_locations = 2;
    
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, locations, num_locations);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //CGContextDrawLinearGradient(context, gradient, CGPointMake(size.height/2, 0), CGPointMake(size.height/2, size.width), 0);
    
    CGPoint p1 = CGPointMake(size.width/2, 0);
    CGPoint p2 = CGPointMake(size.width/2, size.height);
    CGContextDrawLinearGradient(context, gradient, p1, p2, 0);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGColorSpaceRelease(rgb);
    CGGradientRelease(gradient);
	
    return image;
}

@end


@implementation UIImage (Compatible)

+ (UIImage *)compatibleNotCachedImageNamed:(NSString *)name
{
    UIImage *image = nil;
	
	NSString *extension = [name pathExtension];
	NSString *retinaName = [[name stringByDeletingPathExtension] stringByAppendingString:@"@2x"];
	
	if (extension.length != 0)
	{
		retinaName = [retinaName stringByAppendingPathExtension:extension];
		image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:retinaName]];
	}
		
	if (image == nil)
	{
		image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:name]];
	}
	
    return image;
}

+ (UIImage *)compatibleImageNamed:(NSString *)name
{
    return [self compatibleImageNamed:name shouldCache:YES];
}

+ (UIImage *)compatibleImageNamed:(NSString *)name andNameOf4Inch:(NSString *)nameOf4Inch
{
    return [self compatibleImageNamed:name andNameOf4Inch:nameOf4Inch shouldCache:YES];
}

+ (UIImage *)compatibleImageNamed:(NSString *)name shouldCache:(BOOL)cache
{
    UIImage *image = nil;
    if (iPhone5)
	{
        NSString *extension = [name pathExtension];
        
        NSString *nameOf4Inch = [[name stringByDeletingPathExtension] stringByAppendingString:@"-568h"];
        
        if (extension.length != 0)
            nameOf4Inch = [nameOf4Inch stringByAppendingPathExtension:extension];
        
        if (cache)
		{
            image = [UIImage imageNamed:nameOf4Inch];
        }
        else
		{
            image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:nameOf4Inch]];
            
            if (image == nil)
			{
                image = [[self class] compatibleNotCachedImageNamed:name];
            }
        }
    }
    else
	{
        if (cache)
		{
            image = [UIImage imageNamed:name];
        }
        else
		{
            image = [[self class] compatibleNotCachedImageNamed:name];
        }
    }
    
    return image;
}

+ (UIImage *)compatibleImageNamed:(NSString *)name andNameOf4Inch:(NSString *)nameOf4Inch shouldCache:(BOOL)cache
{
    UIImage *image = nil;
    if (iPhone5)
	{
        if (cache)
		{
            image = [UIImage imageNamed:nameOf4Inch];
        }
        else
		{
            image = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:nameOf4Inch]];
            
            if (image == nil)
			{
                image = [[self class] compatibleNotCachedImageNamed:name];
            }
        }
    }
    else
	{
        if (cache)
		{
            image = [UIImage imageNamed:name];
        }
        else
		{
            image = [[self class] compatibleNotCachedImageNamed:name];
        }
    }
    return image;
}

@end


